import wenxocr
import gai
import read
import znyj
import re
import json
def trim_string(input_string):
    # 检查字符串长度是否足够删除前7个字符和最后3个字符
    if len(input_string) >= 10:
        # 删除前7个字符和最后3个字符
        trimmed_string = input_string[7:-3]
        return trimmed_string
    else:
        # 如果字符串长度不足，返回原始字符串或者错误信息
        return "输入字符串长度不足，无法删除指定数量的字符。"
def ocr(url):
   result =  wenxocr.shi_bie(url)

   return result
def se_read():
    con,records  = read.read()
    for row in records:
        if(row[5]==0):
            id = row[0]#id
            #print(f"id:{id}")
            discipline = row[1]#学科名字
            #print(f"学科:{discipline}")
            rulse = row[2]#改卷规则
            #print(f"规则:{rulse}")
            standard = row[3]#标准答案
            #print(f"标准答案:{standard}")
            student1 = row[7]#学生图片作答作答 m
            #print(f"图片url:{student1}")
            student2 = row[6]#文字作答
            #print(f"学生文字作答:{student2}")
            resu =sho_or_image(discipline=discipline,rules=rulse,standard=standard,student1 = student1,student2 = student2)
            print(resu)
            print("批改成功")
            return save(con,resu,id)
def save(con,huda,id):
    huda_str = json.dumps(huda)
    huda_str = trim_string(huda)
    cursor = con.cursor()
    #print(huda)
    update_sql = "UPDATE tasks SET correctionResult = %s, status = 0 WHERE id = %s;"
    cursor.execute(update_sql,(huda_str,id))
    con.commit()
    print("试卷结果保存成功")
    print(6666)
    return huda_str
def sho_or_image(discipline,rules,standard,student1,student2):
    if(student2==""):
        resu_shi = ocr(student1)
        print("图片答案识别成功")
        return znyj.znyj(discipline,rules,standard,resu_shi)
    else:
        print("文字答案载入成功")
        return znyj.znyj(discipline,rules,standard,student2)
if __name__ == '__main__':
    se_read()